import * as Cesium from 'cesium'
import { TiandituImagercyProvider } from './mapConfig'

interface ViewerConfig {
  creditContainerId: string
  containerId: string
  accessToken: string
  tiandituKey: string
}
class CesiumViewer {
  private viewer: Cesium.Viewer | null = null
  private tiandituProvider: TiandituImagercyProvider | null = null
  constructor(private config: ViewerConfig) {
    this.tiandituProvider = new TiandituImagercyProvider({
      accessToken: config.accessToken,
      tiandituKey: config.tiandituKey,
    })
  }
  /**
   * 初始化Cesium Viewer
   */
  async initViewer(): Promise<Cesium.Viewer> {
    //等待世界地形就绪
    const terrainProvider = await Cesium.createWorldTerrainAsync({
      requestVertexNormals: true, //请求法向量
      requestWaterMask: true, //请求水印
    })

    // 创建天地图影像和标注图层
    const imgProvider = this.tiandituProvider?.createImageryProvider()
    const ciaProvider = this.tiandituProvider?.createCiaProvider()
    //创建Viewer
    this.viewer = new Cesium.Viewer(this.config.containerId, {
      baseLayerPicker: false,
      animation: false,
      geocoder: false,
      fullscreenButton: false,
      homeButton: false,
      infoBox: false,
      sceneModePicker: false,
      selectionIndicator: true,
      timeline: false,
      navigationHelpButton: false,
      baseLayer: new Cesium.ImageryLayer(imgProvider),
      creditContainer: this.config.creditContainerId, //不显示版权信息
      terrainProvider,
    })
    if (ciaProvider) {
      this.viewer.imageryLayers.addImageryProvider(ciaProvider)
    }
    return this.viewer
  }
}
const cesiumViewer = new CesiumViewer({
  creditContainerId: 'creditContainer',
  containerId: 'cesiumContainer',
  accessToken: import.meta.env.VITE_CESIUM_ION_KEY,
  tiandituKey: import.meta.env.VITE_TDT_KEY,
})

export { cesiumViewer }
